
import './detail.less'
import dictsMixin from '@/mixins/dicts'

import proposal from '@/mixins/proposal'
import filters from '@/mixins/filters'
import layer from '@/components/layer'
import { TreeToArray } from '@/utils'

export default {
	mixins: [dictsMixin, proposal],
	data() {
		return {
			infoType: '',
			caseStatus: false,
			filter: filters.filters,
			search: {
				loading: false,
				list: [],
				timer: null
			},
			sexList: [
				{
					value: 1,
					label: '男',
				},
				{
					value: 2,
					label: '女',
				}
			],
			isChange: [
				{
					value: 1,
					label: '是',
				},
				{
					value: 0,
					label: '否',
				}
			],
			clueDetail: {
				clueInformer: {},
				clueBeReported: {},
				clueInfo: [],
				caseTrack: [],

				customer: [{}],
				caseBeReported: [{}]
			},
			evidence: {
				filter: {
					clueInfoId: this.$route.query.id,
					pageBean: {
						pageIndex: 1,
						pageSize: 10
					},
				},
				data: []
			},
			record: {
				filter: {
					clueInfoId: this.$route.query.id,
					pageBean: {
						pageIndex: 1,
						pageSize: 10
					},
				},
				data: []
			},
			track: {
				filter: {
					clueInfoId: this.$route.query.id,
					pageBean: {
						pageIndex: 1,
						pageSize: 10
					},
				},
				data: []
			},
			// 添加 ---（证据、报告）
			addInfoLayer: {
				url: '',
				show: false,
				title: '',
				text: '',
				form: {
					remark: '',
					clueInfoId: this.$route.query.id,
				},
				uploadUrl: api.API_BASE_URL + '/upload',
				fileList: [],
				fileNames: []
			},
			// 分部负责人列表
			deptPrincipalList: [],
			// 分部负责人
			deptPrincipal: {
				name: ''
			},
			//所属营业部
			salesDeptData: {
				loading: false,
				timer: null,
				list: []
			},

			id: this.$route.query.id || 0,
			userInfo: this.$store.state.common.userInfo,
			tabIndex: 0,
			// 作废
			invalid: {
				layer: {
					show: false,
					title: '作废'
				},
				form: {}
			},
			// 提案
			proposalLayer: {
				show: false,
				title: '提案',
				tips: '是否确认提案申请？'
			},
			// 取消提案
			cancelProposalLayer: {
				show: false,
				title: '取消提案',
				tips: '是否确认提案申请？'
			}
		}
	},
	computed: {
		deptList() {
			return TreeToArray({ tree: this.$store.state.system.deptList })
		}
	},
	components: {
		layer
	},
	beforeMount() {
		//this.searchBusinessMethod();
	},
	mounted() {
		this.$store.dispatch('setBreadData', [
			{
				name: '线索详情'
			}
		])

		this.proposalTableData.data = []
		this.proposalTableData.type = 1
		this.proposalTableData.ajax = true

		this.getClueDetail()
		this.getEvidence()
		//this.getTrack()

		if (this.$store.state.system.deptList && this.$store.state.system.deptList.length == 0) {
			this.$store.dispatch('getDeptList')
		}
	},
	methods: {
		tabClick(i) {
			this.tabIndex = i
		},
		// 线索详情
		getClueDetail() {
			api.queryClueInfoById({ id: this.id }).then(res => {
				if (res.clueInformer.reflectSex != undefined) {
					res.clueInformer.reflectSexName = res.clueInformer.reflectSex == 1 ? '男' : '女'
				}
				if (res.clueInformer.managerChange != undefined) {
					res.clueInformer.managerChangeName = res.clueInformer.managerChange == 1 ? '是' : '否'
				}
				res.clueInformer.creditDate = res.clueInformer.creditDate ? this.filter.formatDate(res.clueInformer.creditDate, 'yyyy-MM-dd') : ''
				res.clueInformer.borrowDate = res.clueInformer.borrowDate ? this.filter.formatDate(res.clueInformer.borrowDate, 'yyyy-MM-dd') : ''
				res.clueInfo.clueDate = res.clueInfo.clueDate ? this.filter.formatDate(res.clueInfo.clueDate, 'yyyy-MM-dd') : ''

				this.deptPrincipal.name = res.clueInfo.salesName

				if (res.clueInfo.source) {
					let _obj = this.dicts.sourceType.find(o => o.value == res.clueInfo.source)
					if (_obj) {
						res.clueInfo.sourceName = _obj.name
					}
				}
				if (res.clueInfo.product) {
					let _obj = this.dicts.productType.find(o => o.value == res.clueInfo.product)
					if (_obj) {
						res.clueInfo.productName = _obj.name
					}
				}

				if (res.clueInfo.riskCategory) {
					let _category = this.dicts.riskCategory.find(item => item.value == res.clueInfo.riskCategory)
					if (_category) {
						this.riskCategoryForm.id = _category.id
						if (res.clueInfo.riskType) {
							this.riskCategoryChange(_category.id)
							this.riskTypeForm.value = res.clueInfo.riskType
						}
						if (res.clueInfo.riskLevel) {
							this.riskTypeChange(res.clueInfo.riskType)
							this.riskLevelForm.value = res.clueInfo.riskLevel
						}
					}
				}

				this.clueDetail = res
				this.caseStatus = this.clueDetail.clueInfo.clueStatus !== 0 && this.clueDetail.clueInfo.clueStatus !== 3

				this.clueDetail.customer = [{}]
				this.clueDetail.caseBeReported = [{}]

				// 举报人所属营业部
				if (this.clueDetail.clueInformer.salesDeptCode) {
					let _obj = {}
					_obj.id = this.clueDetail.clueInformer.salesDeptCode
					_obj.deptName = this.clueDetail.clueInformer.salesDeptName
					this.salesDeptData.list = []
					this.salesDeptData.list.push(_obj)
				}

				this.getProposalData(1)

			}).catch(res => {
				console.log(res)
			})
		},
		// 线索轨迹
		getTrack() {
			api.clueTrackList(this.track.filter).then(res => {
				if (res.totalCount > 0) {
					this.track.total = res.totalCount;
					this.track.data = res.list;
				}
			}, error => { })
		},

		// 搜索被举报人所属公司和被举报人所属部门
		searchBusinessMethod(val) {
			if (this.salesDeptData.timer) {
				clearTimeout(this.salesDeptData.timer)
			}
			if (val !== '') {
				this.search.loading = true;
				this.search.timer = setTimeout(() => {
					api.queryDepartment({
						name: val
					}).then(res => {
						this.search.loading = false
						this.search.list = res.department
					}).catch(res => {
						console.log(res)
					})
				}, 200)
			}
			else {
				this.search.list = []
			}
		},
		// 查询营业部详情
		getSalesDeptJc(id) {
			if (id) {
				this.salesDeptData.list = []
				api.getSalesDeptJc({ id: id })
					.then(res => {
						this.salesDeptData.list.push(res)
					})
					.catch(err => {
						console.log(err)
					})
			}
		},
		// 请搜索所属营业部
		searchSalesDept(val) {
			if (this.salesDeptData.timer) {
				clearTimeout(this.salesDeptData.timer)
			}
			if (val !== '') {
				this.salesDeptData.loading = true
				this.salesDeptData.timer = setTimeout(() => {
					let _data = {}
					_data.deptName = val
					_data.pageBean = {}
					_data.pageBean.pageIndex = 1
					_data.pageBean.pageSize = 1000
					api.queryDeptJc(_data)
						.then(res => {
							this.salesDeptData.loading = false
							this.salesDeptData.list = res.list
						})
						.catch(err => {
							this.salesDeptData.loading = false
							console.log(err)
						})
				}, 200)
			} else {
				this.salesDeptData.list = []
			}
		},
		// 举报人所属营业部
		salesDeptChange(val) {
			if (val) {
				let _obj = this.salesDeptData.list.find(d => d.id == val)
				if (_obj) {
					this.clueDetail.clueInformer.salesDeptName = _obj.deptName
				}
			}
		},
		// 证据 -- 分页
		evidenceCurrentChange(val) {
			this.evidence.filter.pageBean.pageIndex = val;
			this.getEvidence();
		},
		// 证据 -- 条数改变
		evidenceSizeChange(val) {
			this.evidence.filter.pageBean.pageIndex = 1;
			this.evidence.filter.pageBean.pageSize = val;
			this.getEvidence();
		},
		// 获取证据
		getEvidence() {
			api.clueEvidenceList(this.evidence.filter).then(res => {
				this.evidence.total = res.totalCount
				res.list.map(item => {
					item.cdate = this.filter.formatDate(item.cdate)
					return item
				})
				this.evidence.data = res.list
			}, error => { })
		},
		// 报告 -- 分页
		trackCurrentChange(val) {
			this.track.filter.pageBean.pageIndex = val;
			this.getTrack();
		},
		// 报告 -- 条数改变
		trackSizeChange(val) {
			this.track.filter.pageBean.pageIndex = 1;
			this.track.filter.pageBean.pageSize = val;
			this.getTrack();
		},
		// 添加证据 -- 添加报告 -- 弹窗
		showInfoLayer(type) {
			this.addInfoLayer.form = {}
			this.addInfoLayer.fileList = []
			this.infoType = type;
			// 证据
			if (type === 'clueEvidences') {
				this.addInfoLayer.text = '上传证据文件'
				this.addInfoLayer.title = '添加证据'
				this.addInfoLayer.url = 'addclueEvidence'
			}

			this.addInfoLayer.show = true;
		},
		// 删除证据
		delEvidence(id) {
			api.deleteClueEvidence({ id: id }).then(res => {
				this.$msg.success('删除成功');
				this.getEvidence();
			}).catch(res => {
				console.log(res)
			})
		},

		// 上传文件之前验证格式
		beforeUpload(file) {
			if (file.size == 0) {
				this.$msg.error('上传文件大小不能为0B!')
				return false
			}
			// // const isIamge = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
			// const limitSize = file.size / 1024 / 1024 < 100;

			// // if (!isIamge) {
			// //     this.$msg.error('上传文件只能是 JPG png gif格式!');
			// // }
			// if (!limitSize) {
			// 	this.$msg.error('上传文件大小不能超过 100MB!');
			// }
			// // return isIamge && limitSize;
			// return limitSize;
		},
		// 文件列表移除文件时的钩子
		removeUploadFile(file, fileList) {
			this.addInfoLayer.fileList = fileList
		},
		// 上传文件成功
		uploadSuccess(res, file) {
			var _res = file.response;
			if (_res.code == 10000) {
				let _obj = {}
				_obj.name = file.name
				_obj.url = _res.data.url
				this.addInfoLayer.fileList.push(_obj)
			}
			else {
				this.$msg.error(_res.msg);
			}
		},
		// 
		infoSave() {
			if (this.addInfoLayer.fileList && !this.addInfoLayer.fileList.length) {
				this.$msg.error('请' + this.addInfoLayer.text)
				return false
			}
			this.addInfoLayer.fileList.forEach(item => {
				let _obj = {}
				_obj.fileName = item.name
				_obj.fileUrl = item.url
				if (this.addInfoLayer.form.remark) {
					_obj.remark = this.addInfoLayer.form.remark
				}
				if (this.addInfoLayer.form.content) {
					_obj.content = this.addInfoLayer.form.content
				}
				_data[this.infoType].push(_obj)
			})

			api.addClueEvidence(_data).then(res => {
				this.$msg.success('添加成功')
				this.addInfoLayer.show = false
				this.getEvidence();
			}).catch(res => {
				console.log(res)
			})
		},
		// 保存信息
		saveDeatil() {
			this.clueDetail.clueInformer.creditMoney = this.clueDetail.clueInformer.creditMoney ? parseInt(this.clueDetail.clueInformer.creditMoney).toFixed(2) : '';
			this.clueDetail.clueInformer.borrowMoney = this.clueDetail.clueInformer.borrowMoney ? parseInt(this.clueDetail.clueInformer.borrowMoney).toFixed(2) : '';

			// 赋值code
			// if (this.search.list.length > 0) {
			// 	this.clueDetail.clueInformer.salesDeptCode = this.search.list.find(ss => {
			// 		return ss.name == this.clueDetail.clueInformer.salesDeptName
			// 	}).code
			// }


			this.clueDetail.clueInfo.salesName = this.deptPrincipal.name

			if (this.riskCategoryForm.id) {
				let _category = this.dicts.riskCategory.find(item => item.id == this.riskCategoryForm.id)
				if (_category) {
					this.clueDetail.clueInfo.riskCategory = _category.value
				}
			}
			if (this.riskTypeForm.value) {
				this.clueDetail.clueInfo.riskType = this.riskTypeForm.value
			}
			if (this.riskLevelForm.value) {
				this.clueDetail.clueInfo.riskLevel = this.riskLevelForm.value
			}

			api.editClue(this.clueDetail).then(res => {
				this.$msg.success('保存成功');
			}).catch(res => {
				console.log(res)
			})
		},
		//下载文件
		downloadFile(url) {
			let splitUrl = url.split("downLoad?")[1]
			let splitPath = splitUrl.split('path=')[1]
			let path = splitPath.split('&fileName=')[0];
			let fileName = splitPath.split('&fileName=')[1];

			api.download({ path: path, fileName: fileName }).then(res => {
				let $a = document.createElement('a');
				$a.setAttribute('href', res.base64);
				$a.setAttribute('download', res.fileName);
				$a.setAttribute('target', '_blank');
				$a.click();
			}).catch(res => {
				console.log(res)
			})
		},
		// 选择所属分部
		selectSalesDeptName(name) {
			this.deptPrincipal = {}
			let id = this.deptList.find(res => res.name === name).id
			api.queryUser({
				deptId: id,
				pageSize: 100,
				pageIndex: 1
			}).then(res => {
				this.deptPrincipalList = res.list
			}).catch(res => {
				console.log(res)
			})
		},

		// 作废弹窗
		showInvalidLayer() {
			this.invalid.layer.show = true
			this.invalid.form = {}
		},
		// 作废
		clueInvalid() {
			if (!this.invalid.form.abolishInfo) {
				this.$msg.error('请输入作废原因')
				return
			}
			this.invalid.form.id = this.id
			api.abolishClue(this.invalid.form).then(res => {
				this.$msg.success('线索作废成功')
				this.invalid.layer.show = false
			}).catch(err => {
				console.log(err)
			})

		},
		// 提案弹窗
		showProposalLayer() {
			this.proposalLayer.show = true
		},
		// 提案
		clueProposal() {
			api.switchClue({ id: this.id }).then(res => {
				this.$msg.success('线索提案成功')
				this.proposalLayer.show = false
			}).catch(err => {
				console.log(err)
			})
		},
		// 提案弹窗
		showCancelProposalLayer() {
			this.cancelProposalLayer.show = true
		},
		// 取消提案
		cancelProposal() {
			api.cancelClue({ id: this.id }).then(res => {
				this.$msg.success('线索提案成功')
				this.cancelProposalLayer.show = false
			}).catch(err => {
				console.log(err)
			})
		},
		// 编辑
		editClue() {
			this.$router.push('/clue/add?id=' + this.id)
		},
		// 返回上一页
		goBack() {
			this.$router.go(-1)
		}
	}
}